package com.biqee.framework.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import com.biqee.constant.SystemConstant;
import com.biqee.util.StringUtil;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionInvocation;

public class AdminPermissionInterceptor implements
		com.opensymphony.xwork.interceptor.Interceptor {

	private static final long serialVersionUID = 1L;

	@Override
	public void destroy() {

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result = null;
		if (before(invocation)) {
			result = invocation.invoke();
		} else {
			ActionContext ctx = ActionContext.getContext();
			HttpServletRequest request = (HttpServletRequest) ctx
					.get(ServletActionContext.HTTP_REQUEST);
			// String url = EnvUtil.get("webUrl");
			StringBuffer url = new StringBuffer();
			url.append(request.getRequestURI());
			if (StringUtil.isNotBlank(request.getQueryString())) {
				url.append('?');
				url.append(request.getQueryString());
			}
			String redirectUrl = URLEncoder.encode(url.toString(),
					SystemConstant.DEFAULT_CHARTSET);
			ctx.getContextMap().put("redirectUrl", redirectUrl);
			result = "login";
		}
		return result;
	}

	private boolean before(ActionInvocation invocation) {

		Boolean adminPermission = (Boolean) invocation.getInvocationContext()
				.getSession().get("admin");

		return adminPermission == null ? false : adminPermission;

		// String url =
		// request.setAttribute("redirctUrl",request. );

	}

}
